package com.powernode.boss.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powernode.boss.common.constants.SysConst;
import com.powernode.boss.common.enums.PublicStatus;
import com.powernode.boss.common.enums.SysCode;
import com.powernode.boss.common.exceptions.type.SysException;
import com.powernode.boss.dao.entity.PmsOperator;
import com.powernode.boss.dao.mapper.PmsOperatorMapper;
import com.powernode.boss.models.dto.OperatorLoginDto;
import com.powernode.boss.models.request.OperatorLoginRequest;
import com.powernode.boss.service.OperatorService;
import com.powernode.boss.tools.JWTUtil;
import com.powernode.boss.tools.RedisHelper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OperatorServiceImpl implements OperatorService {
    @Resource
    private PmsOperatorMapper pmsOperatorMapper;

    @Resource
    private RedisHelper redisHelper;

    @Override
    public OperatorLoginDto login(OperatorLoginRequest loginRequest) {
        //从数据库获取login_name对应用户，取出salt值，密码和loginRequest比较
        PmsOperator operator=pmsOperatorMapper.selectOne(new QueryWrapper<PmsOperator>()
                .eq("login_name",loginRequest.getLoginName()));

        if (operator==null){
            throw new SysException(SysCode.OPERATOR_LOGIN_NAME_ERROR);
        }
        String status = operator.getStatus();
        if (status.equals(PublicStatus.DISABLE)){
            throw new SysException(SysCode.OPERATOR_DISABLE_ERROR_ERROR);
        }
        //取出salt值
        String salt = operator.getSalt();
        String loginPwd = operator.getLoginPwd();
        //数据库密码 = md5(前端提交密码+salt)
        String loginSaltPwd = loginRequest.getLoginPwd() + salt;
        String requestPwd = DigestUtil.md5Hex(loginSaltPwd);
        if (!(requestPwd.equals(loginPwd))){
            throw new SysException(SysCode.OPERATOR_NAME_PWD_ERROR);
        }
        //登陆成功，计算jwt
        String jwtstr=JWTUtil.createJWT(String.valueOf(operator.getId()), 120);

        //存储jwt到Redis
        String jwtKey = SysConst.OPERATOR_JWT_TOKEN + operator.getId();
        Map<String, String> jwtData = new HashMap<>();
        jwtData.put("jwt", jwtstr);
        jwtData.put("type", operator.getType());
        jwtData.put("loginTime", new SimpleDateFormat("yyyyMMddHHmss").format(new Date()));

        redisHelper.setHashAll(jwtKey, jwtData, TimeUnit.MINUTES, 120);
        return new OperatorLoginDto(operator.getId(), operator.getShowName(), jwtstr);

    }
}
